#!/usr/bin/env python
# encoding: UTF-8
"""models imitates some (very few) features of the django's models module

You can subclass Row and define some attributes as Field and you will have a
convenience attribute insert_sql """

__version__ = "$Id: models.py 38 2010-04-06 09:08:15Z sedlakf $"

import logging

log = logging.getLogger("models")

class MetaRow(type):
    """Metaclass for Row objects
    - prepares insert_sql attribute"""
    def __init__(cls, name, ancestors, dictionary):
        type.__init__(cls, name, ancestors, dictionary)
        fields = []
        for name, value in dictionary.iteritems():
            if isinstance(value, Field) and name != "id":
                fields.append(name)
        if len(fields) > 0:
            sql = ("INSERT INTO %s ("
                + ', '.join(fields) + ") VALUES ("
                + ', '.join(["?"]*len(fields)) + ");")
            cls.fields = fields
            cls.insert_sql = sql

class Field(object):
    pass

class Row(object):
    insert_sql = None
    cursor = None
    __metaclass__ = MetaRow
    def __init__(self, table):
        self.insert_sql = self.insert_sql % table
        self.table = table

    def save(self):
        """Saves to the db. Remember to set the attribute cursor to whichever db
        cursor you want to use before calling this method!"""
        values = [getattr(self, field) for field in self.fields]
        #print self.insert_sql
        #print len(values)
        #print len(self.fields)
        log.debug(self.insert_sql + " " + str(values))
        self.cursor.execute(self.insert_sql, values)
        log.debug(" -> row " + str(self.cursor.lastrowid))
        return self.cursor.lastrowid
    
